﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Golf
{
    /// <summary>
    /// FileDownloadHandler 的摘要说明
    /// </summary>
    public class FileDownloadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string sFileToDownload = context.Request.QueryString["filePath"];

            if (!string.IsNullOrEmpty(sFileToDownload))
            {
                byte[] decbuff = Convert.FromBase64String(sFileToDownload);

                sFileToDownload = System.Text.Encoding.UTF8.GetString(decbuff);


                var fi = new FileInfo(sFileToDownload);
                if (fi.Exists)
                {
                    long lFileLength = fi.Length;

                    //clear response first
                    context.Response.Clear();
                    context.Response.ClearHeaders();

                    //set content type to file type eg exl
                    context.Response.ContentType = string.Format("text/{0}", Path.GetExtension(sFileToDownload)); //"application/octet-stream"; 

                    context.Response.AppendHeader("content-disposition",
                    string.Format("attachment; filename={0}", Path.GetFileName(sFileToDownload)));

                    context.Response.AppendHeader("Content-Length", lFileLength.ToString());

                    //may need to use TransmitFile here but this is only available as of ASP.NET 2.0
                    //- might be better for large files as it streams without buffering
                    context.Response.WriteFile(sFileToDownload);
                    context.Response.Flush();
                    context.Response.End();
                }
                else
                {
                    context.Response.Write("Nothing to do");
                }
            }
            else
            {
                context.Response.Write("Nothing to do");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}